package com.jintian.smart.kernel.core.dto;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("serial")
public class MapBean extends HashMap<String, Object> {
    private Map<String, String> attrAlias;

    public MapBean setAttrAlias(Map<String, String> attrAlias) {
        this.attrAlias = attrAlias;
        return this;
    }

    public MapBean() {
        super(4);
    }

    public MapBean(Map<? extends String, ? extends Object> map) {
        super(map);
    }

    protected <T> T get(String key, Class<T> clazz, T defaultValue) {
        Object value = this.get(key);
        if (value == null) {
            return defaultValue;
        }
        if (clazz.isAssignableFrom(value.getClass()))
            return clazz.cast(value);
        else if (value instanceof Map && MapBean.class.isAssignableFrom(clazz)) {
            try {
                Constructor<T> constructor = clazz.getConstructor(Map.class);
                return constructor.newInstance(value);
            } catch (Exception e) {
                throw new IllegalArgumentException(e);
            }
        } else {
            throw new ClassCastException(value.getClass().getName() + "不能转换为" + clazz.getName());
        }
    }

    protected <T> T get(String key, Class<T> clazz) {
        return this.get(key, clazz, null);
    }

    protected Object get(String key) {
        if (attrAlias != null && attrAlias.containsKey(key)) {
            return super.getOrDefault(key, super.get(attrAlias.get(key)));
        }
        return super.get(key);
    }
}
